//
//  TaskViewController.m
//  WorkingResult
//
//  Created by 河野 智遵 on 11/08/15.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "TaskTabViewController.h"
#import "Task.h"

@implementation TaskTabViewController

#pragma mark - View lifecycle

@synthesize model;

- (void)viewDidLoad
{
    [super viewDidLoad];

    taskList = [[TaskListViewController alloc] initWithStyle:UITableViewStyleGrouped];
    taskList.moveToAddingTaskEditorActionTarget = self;
    taskList.moveToAddingTaskEditorAction = @selector(on_taskList_moveToAddingTaskEditor);
    
    taskList.model = self.model;
    taskList.moveToUpdatingTaskEditorActionTarget = self;
    taskList.moveToUpdatingTaskEditorAction = @selector(on_taskList_moveToUpdatingTaskEditor);

    taskEdit = [[TaskEditViewController alloc] init];
    taskEdit.doneActionTarget = self;
    taskEdit.doneAction = @selector(on_taskEdit_done);
    
    taskListNavigation = [[UINavigationController alloc] initWithRootViewController:taskList];
    taskEditNavigation = [[UINavigationController alloc] initWithRootViewController:taskEdit];
    
    [self.view addSubview:taskListNavigation.view];
}

- (void)on_taskList_moveToUpdatingTaskEditor
{
    [taskEdit clear];
    taskEdit.mode = UPDATE;
    taskEdit.task = [model taskAtIndex:[taskList getSelectedTaskIndex]];
    [taskListNavigation pushViewController:taskEdit animated:YES];
}

- (void)on_taskEdit_done
{
    switch (taskEdit.mode)
    {
        case ADD:
            [self.model addTask:taskEdit.task];
            break;
        case UPDATE:
            [self.model updateTask:taskEdit.task index:taskList.selectedTaskIndex];
            break;
        default:
            break;
    }
    [taskList.tableView reloadData];
    [taskList viewWillAppear:YES]; // ←これは書かなくても動作するね・・・
}

-(void)on_taskList_moveToAddingTaskEditor
{
    [taskEdit clear];
    taskEdit.mode = ADD;
    [taskListNavigation pushViewController:taskEdit animated:YES];
}

- (void)viewDidUnload
{
    [taskList release];
    [taskListNavigation release];
    [taskEdit release];
    [taskEditNavigation release];
    [self.model release];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
